/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.gtask.remote;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

public class GTaskSyncService extends Service {
    public final static String ACTION_STRING_NAME = "sync_action_type";// 定义同步操作类型的字符串标识

    public final static int ACTION_START_SYNC = 0;// 定义启动同步操作的常量

    public final static int ACTION_CANCEL_SYNC = 1;// 定义取消同步操作的常量

    public final static int ACTION_INVALID = 2;// 定义无效操作的常量

    public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";// 广播消息名称

    public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";// 广播消息中是否正在同步的标志

    public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";// 广播消息中的进度消息

    private static GTaskASyncTask mSyncTask = null;// 静态成员变量：存储同步任务的实例

    private static String mSyncProgress = "";// 静态成员变量：存储同步进度的消息

    private void startSync() {// 启动同步任务
        if (mSyncTask == null) {// 如果同步任务为空
            mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {//创建并执行新的同步任务
                public void onComplete() {
                    mSyncTask = null;  // 清空同步任务
                    sendBroadcast("");  // 发送同步完成的广播
                    stopSelf();  // 停止服务
                }
            });
            sendBroadcast("");  // 发送同步开始的广播
            mSyncTask.execute();  // 执行同步任务
        }
    }

    private void cancelSync() {// 取消同步任务
        if (mSyncTask != null) {
            mSyncTask.cancelSync();
        }
    }

    @Override
    public void onCreate() {
        mSyncTask = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {// 处理启动服务时传入的意图
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {// 根据意图中的操作类型来决定执行什么操作
            switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
                case ACTION_START_SYNC:
                    startSync();// 启动同步任务
                    break;
                case ACTION_CANCEL_SYNC:
                    cancelSync();// 取消同步任务
                    break;
                default:
                    break;
            }
            return START_STICKY;// 保持服务在后台运行，直到明确停止
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onLowMemory() {// 如果内存低时，取消正在进行的同步任务
        if (mSyncTask != null) {
            mSyncTask.cancelSync();
        }
    }

    public IBinder onBind(Intent intent) {
        return null;
    } // 服务绑定时调用，但本服务不允许绑定，因此返回null

    public void sendBroadcast(String msg) {// 发送广播消息，通知同步进度
        mSyncProgress = msg;// 更新同步进度消息
        Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
        intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);// 是否正在同步
        intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);// 当前进度消息
        sendBroadcast(intent);// 发送广播
    }

    public static void startSync(Activity activity) { // 静态方法：在Activity中启动同步服务
        GTaskManager.getInstance().setActivityContext(activity);// 设置Activity上下文
        Intent intent = new Intent(activity, GTaskSyncService.class);
        intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
        activity.startService(intent);// 启动服务
    }

    public static void cancelSync(Context context) {// 静态方法：取消同步服务
        Intent intent = new Intent(context, GTaskSyncService.class);
        intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
        context.startService(intent);// 启动服务
    }

    public static boolean isSyncing() {
        return mSyncTask != null;
    }// 静态方法：检查是否正在同步

    public static String getProgressString() {
        return mSyncProgress;
    } // 静态方法：获取当前同步的进度消息
}
